
package com.axc.gallery2.dbhelper;

import java.text.MessageFormat;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

/**
 * 数据库操作辅助基类
 *
 */

public class DbHelper extends SQLiteOpenHelper implements DBInfo {

    SQLiteDatabase db;
    private Context context;

    public DbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        this.context = context;
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        System.out.println("oncreate");
        createTalbe(db, TABLE_ALBUM_NAME, new String[] {
                TABLE_ALBUM_COLUNM_NAME, TABLE_ALBUM_COLUNM_DESCRIPTION
        });
        createTalbe(db, TABLE_IMAGES_NAME, new String[] {
                TABLE_IMAGES_COLUNM_LOCATION, TABLE_IMAGES_COLUNM_ALBUMID
        });
        createTalbe(db, TABLE_TIME_NAME, new String[] {});
        createTalbe(db, TABLE_NETALBUMDETAILED, new String[] {
                AID, URL, UID, NAME, SIZE, TYPE
        });
        createTalbe(db, TABLE_NETALBUMINFO, new String[] {
                AID, PID, S_URL, B_URL, L_URL
        });
        createTalbe(db, TABLE_NETUPLOAD, new String[] {
            PATH
        });
    }

    // 获取是否第一次运行程序
    public boolean getIsFirstRun() {
        System.out.println("getIsFirstRun");
        if (isTableExist(TABLE_TIME_NAME)) {
            System.out.println("TableExist");
            db = getWritableDatabase();
            db.execSQL("DROP TABLE  IF EXISTS " + TABLE_TIME_NAME);
            db.close();
            return true;
        }
        return false;
    }

    // 判断是否存在表
    protected boolean isTableExist(String tableName) {
        db = this.getReadableDatabase();

        String sql = "select 1  from sqlite_master where type ='table' and name ='" + tableName
                + "' ";
        Cursor cursor = db.rawQuery(sql, null);
        boolean result = false;
        if (cursor.getCount() > 0) {

            result = true;
        }
        cursor.close();
        db.close();
        return result;
    }

    // 创建表
    protected void createTalbe(SQLiteDatabase db, String tableName, String[] columns) {
        {

            String sql = "Create table " + tableName + "(" + FIELD_ID
                    + " integer primary key autoincrement";

            for (String colunmString : columns) {
                sql += "," + colunmString + " text";
            }
            sql += ")";
            db.execSQL(sql);
        }
    }

    protected Cursor rawQuery(String tableName, String[] columns, String selection,
            String[] selectionArgs, String groupBy, String having, String orderBy) {
        db = this.getReadableDatabase();
        Cursor cursor = db.query(tableName, columns, selection, selectionArgs, groupBy, having,
                " _id desc");

        return cursor;
    }

    protected Cursor rawQuery(String sql, String[] args) {
        db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(sql, args);
        return cursor;
    }

    protected void insert(String tableNameString, String[] columns, String[] values) {
        db = this.getWritableDatabase();
        String sql = "insert into " + tableNameString + "(";
        String valueString = " values('";
        for (int i = 0; i < columns.length; i++) {
            if (i != columns.length - 1) {
                sql += columns[i] + ",";
                valueString += values[i] + "','";
            } else {
                sql += columns[i] + ")";
                valueString += values[i] + "')";
            }
        }
        sql += valueString;
        System.out.println(sql);
        db.execSQL(sql);
        db.close();

    }

    protected void colseDBbase() {
        if (db.isOpen()) {
            db.close();
        }
    }

    protected void delete(String tableName, int id) {
        db = this.getWritableDatabase();
        String sqlString = MessageFormat.format("DELETE FROM {0} WHERE {1}={2}"
                , tableName, FIELD_ID, "'" + id + "'");
        db.execSQL(sqlString);
        db.close();
    }
    /**
     * 删除信息
     * @param tableName 表名
     * @param cols 字段
     * @param values 值
     */
    protected void delete(String tableName,String[] cols, String[] values) {
        db = this.getWritableDatabase();
        StringBuilder sBuilder =  new StringBuilder("DELETE FROM ");
        sBuilder.append(tableName);
        sBuilder.append(" where ");
        for (int i=0;i<cols.length;i++) {
            sBuilder.append(cols[i]);
            sBuilder.append("='");
            sBuilder.append(values[i]);
            sBuilder.append("'");
            sBuilder.append(" and ");
        }    
        String sqlString = sBuilder.toString();
        sqlString = sqlString.substring(0,sqlString.lastIndexOf('a'));
        System.out.println(sqlString);
        db.execSQL(sqlString);
        db.close();
    }

    protected void delete(String tableName, String id) {
        db = this.getWritableDatabase();
        String sqlString = MessageFormat.format("DELETE FROM {0} WHERE {1}={2}"
                , tableName, FIELD_ID, "'" + id + "'");
        db.execSQL(sqlString);
        db.close();
    }
    

    // 更新表数据
    protected void update(String tableName, int id, String[] columns, String[] values) {
        db = this.getWritableDatabase();
        String where = FIELD_ID + "=?";
        String[] whereValue = {
            Integer.toString(id)
        };
        ContentValues cv = new ContentValues();
        for (int i = 0; i < columns.length; i++) {
            cv.put(columns[i], values[i]);
        }
        db.update(tableName, cv, where, whereValue);
        db.close();
    }

    // 更新数据库
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (oldVersion != newVersion && db.getVersion() != newVersion) {
            db.setVersion(newVersion);
        }
        db.close();
    }

    // 执行sql语句
    protected void excuteSql(String sql) {
        db = getWritableDatabase();
        db.execSQL(sql);
        db.close();
    }

    public void setContext(Context context) {
        this.context = context;
    }

    public Context getContext() {
        return context;
    }

}
